package com.itheima.reggie.interceptor;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.itheima.reggie.common.EmployeeHolder;
import com.itheima.reggie.common.ResultInfo;
import com.itheima.reggie.damain.Employee;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class LoginCheckinterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //session存储信息
        Employee employee= (Employee) request.getSession().getAttribute("键值对的键");
        if (employee!=null){
            EmployeeHolder.setThreadLocal(employee);
            return true;
        }else {
            //如果未登录，返回错误
            ResultInfo resultInfo=ResultInfo.error("NOTLOGIN");
            String json=new ObjectMapper().writeValueAsString(resultInfo);
            response.getWriter().write(json);
            return false;
        }
    }
//移除
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        EmployeeHolder.remove();
    }
}
